package service

import (
	"backend/curd"
	"backend/define"
	"backend/helper"
	"errors"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"net/http"
)

// 用户登录

func Login(c *gin.Context) {
	in := new(LoginPasswordRequest)
	err := c.ShouldBind(in)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": -1,
			"msg":  err.Error(),
		})
		return
	}

	//  根据账号和密码查询的用户
	sysUser, err := curd.GetUserByUsernamePassword(in.UserName, in.Password)
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			c.JSON(http.StatusOK, gin.H{
				"code": -1,
				"msg":  "用户名或密码错误",
			})
			return
		}
		c.JSON(http.StatusOK, gin.H{
			"code": -1,
			"msg":  "用户名和密码错误",
		})
		return
	}
	// 生成token
	token, err := helper.GenerateToken(sysUser.ID, sysUser.Username, sysUser.RoleId, define.TokenExpire)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": -1,
			"msg":  err.Error(),
		})
		return
	}

	// 刷新token
	refreshToken, err := helper.GenerateToken(sysUser.ID, sysUser.Username, sysUser.RoleId, define.RefreshTokenExpire)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": -1,
			"msg":  err.Error(),
		})
		return
	}

	data := &LoginPasswordReply{
		Token:        token,
		RefreshToken: refreshToken,
	}
	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"data": data,
		"msg":  "登录成功",
	})
}
